package gcu.module.property_money.service;

import com.google.common.collect.Maps;
import gcu.common.context.SecurityContextHolder;
import gcu.module.build.dao.BuildDao;
import gcu.module.build.daomain.Build;
import gcu.module.owner.dao.OwnerDao;
import gcu.module.owner.daomain.Owner;
import gcu.module.property_money.dao.MoneyDao;
import gcu.module.property_money.daomain.PropertyMoney;
import gcu.module.rbac.daomain.User;
import gcu.module.room.dao.RoomDao;
import gcu.module.room.daomain.Room;
import gcu.util.Pager;
import gcu.util.SFormt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by haol on 2016/9/25.
 */
@Service
public class MoneyService {
      @Autowired
      private MoneyDao moneyDao;
      @Autowired
      private OwnerDao ownerDao;
      @Autowired
      private BuildDao buildDao;

      public void addMoney(PropertyMoney money) {
            User user =SecurityContextHolder.getUser();
            money.setHandleId(user.getId());
            money.setCreateTime(SFormt.NOWDATE_y_M_dhms());
            money.setPayInTime(SFormt.NOWDATE_y_M_dhms());
            money.setIsDeadLine(0);
            moneyDao.addMoney(money);
      }

      public void updateMoney(PropertyMoney money) {
            money.setPayInTime(SFormt.NOWDATE_y_M_dhms());
            moneyDao.updateMoney(money);
      }
      public void deleteMoney(int id) {
            moneyDao.deleteMoney(id);
      }
      public PropertyMoney getMoneyByOwnerId(int id) {
           return moneyDao.queryMoneyByOwnerId(id);
      }
      public List<PropertyMoney> queryMoneyList(PropertyMoney money, Pager pager) {
            return moneyDao.queryMoneyList(money, pager);
      }

      @Transactional(readOnly = true)
      public Map<String, Object> get(Integer ownerId) {
            Map<String, Object> map = Maps.newHashMap();
            Owner owner = ownerDao.queryOwnerById(ownerId);
            Build build = buildDao.queryBuildByName(owner.getBuildName());
            map.put("owner",owner);
            PropertyMoney money = moneyDao.queryMoneyByOwnerId(ownerId);
            if (money != null) {
                  money.setPayMoney(build.getPayMoney());
                  map.put("money",money);
            } else {
                  money = new PropertyMoney();
                  money.setPayMoney(build.getPayMoney());
                  map.put("money", money);
            }
            return map;
      }
      public PropertyMoney queryMoneyByOwnerId(Integer ownerId) {
            return moneyDao.queryMoneyByOwnerId(ownerId);
      }
      public void freshenMoney() {
            moneyDao.freshenMoney(SFormt.NOWDATE_y_M_dhms());
      }
}
